package com.tuuzed.android.adapter;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.annotation.ColorInt;
import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import android.support.annotation.Px;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

public class RecyclerViewDivider extends RecyclerView.ItemDecoration {
    private Paint mPaint;
    private Drawable mDivider;
    private int mDividerSize = 1;
    private int mOrientation;
    private static final int[] ATTRS = new int[]{android.R.attr.listDivider};

    @SuppressWarnings("WeakerAccess")
    @IntDef(flag = true, value = {RecyclerView.VERTICAL, RecyclerView.HORIZONTAL})
    @Retention(RetentionPolicy.SOURCE)
    public @interface Orientation {
    }

    public static RecyclerView.ItemDecoration gridLayout(@NonNull Context context) {
        return new RecyclerViewDivider(context, RecyclerView.HORIZONTAL);
    }

    public static RecyclerView.ItemDecoration gridLayout(@NonNull Drawable divider) {
        return new RecyclerViewDivider(RecyclerView.HORIZONTAL, divider);
    }

    public static RecyclerView.ItemDecoration gridLayout(@Px int dividerSize, @ColorInt int dividerColor) {
        return new RecyclerViewDivider(RecyclerView.HORIZONTAL, dividerSize, dividerColor);
    }


    public static RecyclerView.ItemDecoration linearLayout(@NonNull Context context, @Orientation int orientation) {
        return new RecyclerViewDivider(context, orientation);
    }

    public static RecyclerView.ItemDecoration linearLayout(@Orientation int orientation, @NonNull Drawable divider) {
        return new RecyclerViewDivider(orientation, divider);
    }

    public static RecyclerView.ItemDecoration linearLayout(@Orientation int orientation, @Px int dividerSize, @ColorInt int dividerColor) {
        return new RecyclerViewDivider(orientation, dividerSize, dividerColor);
    }

    private RecyclerViewDivider(@NonNull Context context, @Orientation int orientation) {
        if (orientation != RecyclerView.VERTICAL && orientation != RecyclerView.HORIZONTAL) {
            throw new IllegalArgumentException("orientation error");
        }
        mOrientation = orientation;
        TypedArray a = context.obtainStyledAttributes(ATTRS);
        mDivider = a.getDrawable(0);
        a.recycle();
    }


    private RecyclerViewDivider(@Orientation int orientation, @NonNull Drawable divider) {
        mOrientation = orientation;
        mDivider = divider;
        mDividerSize = mDivider.getIntrinsicHeight();
    }


    private RecyclerViewDivider(@Orientation int orientation,
                                @Px int dividerHeight,
                                @ColorInt int dividerColor) {
        mOrientation = orientation;
        mDividerSize = dividerHeight;
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setColor(dividerColor);
        mPaint.setStyle(Paint.Style.FILL);
    }


    //获取分割线尺寸
    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        final RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
        if (layoutManager instanceof GridLayoutManager || layoutManager instanceof StaggeredGridLayoutManager) {
            int itemPosition = ((RecyclerView.LayoutParams) view.getLayoutParams()).getViewLayoutPosition();
            int spanCount = getSpanCount(parent);
            int childCount = parent.getAdapter().getItemCount();
            boolean isFirstRow = isFirstRow(parent, itemPosition, spanCount, childCount);
            int top;
            int left;
            int right;
            int bottom;
            int eachWidth = (spanCount - 1) * mDividerSize / spanCount;
            int dl = mDividerSize - eachWidth;
            left = itemPosition % spanCount * dl;
            right = eachWidth - left;
            bottom = mDividerSize;
            if (isFirstRow) {
                top = (spanCount - 1) * mDividerSize / spanCount;
            } else {
                top = 0;
            }
            outRect.set(left, top, right, bottom);
        } else if (layoutManager instanceof LinearLayoutManager) {
            outRect.set(0, 0, 0, mDividerSize);
        }
    }

    //绘制分割线
    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        super.onDraw(c, parent, state);
        final RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
        if (layoutManager instanceof GridLayoutManager || layoutManager instanceof StaggeredGridLayoutManager) {
            onDrawByGridLayout(c, parent);
        } else if (layoutManager instanceof LinearLayoutManager) {
            onDrawByLinearLayout(c, parent);
        }
    }

    private void onDrawByLinearLayout(Canvas canvas, RecyclerView parent) {
        if (mOrientation == RecyclerView.VERTICAL) {
            drawVertical(canvas, parent);
        } else {
            drawHorizontal(canvas, parent);
        }
    }

    private void onDrawByGridLayout(Canvas canvas, RecyclerView parent) {
        final int childSize = parent.getChildCount();
        for (int i = 0; i < childSize; i++) {
            View child = parent.getChildAt(i);
            RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) child.getLayoutParams();
            //画水平分隔线
            int left = child.getLeft();
            int right = child.getRight();
            int top = child.getBottom() + layoutParams.bottomMargin;
            int bottom = top + mDividerSize;
            drawDivider(canvas, left, top, right, bottom);
            //画垂直分割线
            top = child.getTop();
            bottom = child.getBottom() + mDividerSize;
            left = child.getRight() + layoutParams.rightMargin;
            right = left + mDividerSize;
            drawDivider(canvas, left, top, right, bottom);
        }
    }


    //绘制横向 item 分割线
    private void drawHorizontal(Canvas canvas, RecyclerView parent) {
        final int left = parent.getPaddingLeft();
        final int right = parent.getMeasuredWidth() - parent.getPaddingRight();
        final int childSize = parent.getChildCount();
        for (int i = 0; i < childSize; i++) {
            final View child = parent.getChildAt(i);
            RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) child.getLayoutParams();
            final int top = child.getBottom() + layoutParams.bottomMargin;
            final int bottom = top + mDividerSize;
            drawDivider(canvas, left, top, right, bottom);
        }
    }

    //绘制纵向 item 分割线
    private void drawVertical(Canvas canvas, RecyclerView parent) {
        final int top = parent.getPaddingTop();
        final int bottom = parent.getMeasuredHeight() - parent.getPaddingBottom();
        final int childSize = parent.getChildCount();
        for (int i = 0; i < childSize; i++) {
            final View child = parent.getChildAt(i);
            RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) child.getLayoutParams();
            final int left = child.getRight() + layoutParams.rightMargin;
            final int right = left + mDividerSize;
            drawDivider(canvas, left, top, right, bottom);
        }
    }

    private void drawDivider(Canvas canvas, int left, int top, int right, int bottom) {
        if (mDivider != null) {
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(canvas);
        }
        if (mPaint != null) {
            canvas.drawRect(left, top, right, bottom, mPaint);
        }
    }

    private boolean isFirstRow(RecyclerView parent, int pos, int spanCount, int childCount) {
        RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
        if (layoutManager instanceof GridLayoutManager) {
            //如是第一行则返回true
            return (pos / spanCount + 1) == 1;
        } else if (layoutManager instanceof StaggeredGridLayoutManager) {
            int orientation = ((StaggeredGridLayoutManager) layoutManager)
                    .getOrientation();
            // StaggeredGridLayoutManager 且纵向滚动
            if (orientation == StaggeredGridLayoutManager.VERTICAL) {
                childCount = childCount - childCount % spanCount;
                // 如果是最后一行，则不需要绘制底部
                return pos >= childCount;
            } else {
                // 如果是最后一行，则不需要绘制底部
                return (pos + 1) % spanCount == 0;
            }
        }
        return false;
    }

    private int getSpanCount(RecyclerView parent) {
        // 列数
        int spanCount = -1;
        RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
        if (layoutManager instanceof GridLayoutManager) {
            spanCount = ((GridLayoutManager) layoutManager).getSpanCount();
        } else if (layoutManager instanceof StaggeredGridLayoutManager) {
            spanCount = ((StaggeredGridLayoutManager) layoutManager).getSpanCount();
        }
        return spanCount;
    }

}
